import { useEffect, useState } from 'react';

// 地图区域（与地图数据保持一致）
const mapRegions = ['北京', '上海', '广东', '江苏', '浙江', '四川', '重庆'];

const fetchRegions = async (role: string) => {
  // 只返回地图区域，不包含华北、华东、华南
  return [...mapRegions];
};
const fetchStores = async (region: string) => {
  if (region === '华北') return ['北京一店', '北京二店', '天津店'];
  if (region === '华东') return ['上海一店', '南京店'];
  if (region === '华南') return ['广州店', '深圳店'];
  return [];
};

export default function GlobalFilter() {
  // 简单本地状态模拟全局 store
  const [userRole] = useState('manager');
  const [region, setRegion] = useState('');
  const [store, setStore] = useState('');
  const [dateStart, setDateStart] = useState('');
  const [dateEnd, setDateEnd] = useState('');
  const [availableRegions, setAvailableRegions] = useState<string[]>([]);
  const [availableStores, setAvailableStores] = useState<string[]>([]);

  useEffect(() => { fetchRegions(userRole).then(setAvailableRegions); }, [userRole]);
  useEffect(() => {
    if (region) fetchStores(region).then(setAvailableStores);
    else setAvailableStores([]);
  }, [region]);

  // 日期校验
  const isDateInvalid = dateStart && dateEnd && dateEnd < dateStart;

  // 重置
  const reset = () => {
    setRegion('');
    setStore('');
    setDateStart('');
    setDateEnd('');
  };

  return (
    <div className="global-filter-container">
      <label>区域：</label>
      <select 
        value={region} 
        onChange={e => {setRegion(e.target.value);setStore('')}}
      >
        <option value="">全部</option>
        {availableRegions.map(r => <option key={r} value={r}>{r}</option>)}
      </select>
      
      <label>门店：</label>
      <select 
        value={store} 
        onChange={e => setStore(e.target.value)} 
        disabled={!region}
      >
        <option value="">全部</option>
        {availableStores.map(s => <option key={s} value={s}>{s}</option>)}
      </select>
      
      <label>时间：</label>
      <input 
        type="date" 
        value={dateStart} 
        onChange={e => setDateStart(e.target.value)} 
      />
      <span style={{margin: '0 8px', color: '#718096'}}>-</span>
      <input 
        type="date" 
        value={dateEnd} 
        onChange={e => setDateEnd(e.target.value)} 
      />
      
      {isDateInvalid && (
        <span className="global-filter-error">
          结束时间不能早于开始时间
        </span>
      )}
      
      <button 
        onClick={reset} 
        className="global-filter-reset-btn"
      >
        重置
      </button>
    </div>
  );
} 